package com.trungkent.smsbackup.util;

import java.io.File;
import android.content.Context;

/**
 * This class will create a cache file for storing images in sd card or cache
 * folder of application
 * 
 * @author TrungDH
 * 
 */
public class FileCache {

	private File cacheDir;

	/**
	 * Constructor.
	 * 
	 * @param context
	 */
	public FileCache(Context context) throws IllegalAccessException {
		// Find the dir to save cached images
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			cacheDir = new File(
					android.os.Environment.getExternalStorageDirectory(),
					"BackupSMS");
			if (!cacheDir.exists())
				cacheDir.mkdirs();
		} else {
			throw new IllegalAccessException("sd card is not available");
		}
	}

	/**
	 * get file from sd card/cache folder using this cache
	 * 
	 * @param url
	 * @return File got from sd card/cache folder
	 */
	public File getFile(String url) {
		// I identify images by hashcode. Not a perfect solution, good for the
		// demo.
		String filename = url.replace("/", "").replace(":", "")
				.replace("-", "");

		File f = new File(cacheDir, filename);
		return f;

	}

	/**
	 * Clear all file was stored by using this cache
	 */
	public void clear() {
		File[] files = cacheDir.listFiles();
		for (File f : files)
			f.delete();
	}

}